package com.example.test;

import cn.hutool.crypto.digest.MD5;
import com.google.common.collect.Lists;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * redis hashSlot:16384个
 *
 * @author tuzhijin
 * @version Id: HashSlotUtil.java, v 0.1 2022/11/15 22:36 tuzhijin Exp $$
 */
public class HashSlotUtil {

    public static final Integer HASH_SLOT = 16384;

    private static Map<String, List<Integer>> slotMap;

    private static final MD5 md5;

    static {
        md5 = MD5.create();
        slotMap = new HashMap<>(8);
        List<Integer> list = Lists.newArrayList(0, 5462);
        List<Integer> list2 = Lists.newArrayList(5462, 10923);
        List<Integer> list3 = Lists.newArrayList(10922, 16384);
        slotMap.put("table1", list);
        slotMap.put("table2", list2);
        slotMap.put("table3", list3);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            String orderId = String.valueOf(i);
            System.out.println(dataSharding(md5.digest(orderId).hashCode()));
        }
    }

    public static String dataSharding(Integer hashCode) {
        for (Map.Entry<String, List<Integer>> entry : slotMap.entrySet()) {
            final List<Integer> value = entry.getValue();
            final Integer hashSlot = hashCode % HASH_SLOT;
            if (value.get(0) <= hashSlot && hashSlot < value.get(1)) {
                return entry.getKey();
            }
        }
        return "";
    }

}
